﻿using System;
using System.ComponentModel;
using System.Reflection;

namespace Utility
{
    public static class EnumHelper
    {
        public static string GetEnumDescription(Type type, string enumName)
        {
            try
            {
                FieldInfo field = type.GetField(enumName);
                if (field == null) return "";

                DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
                if (attribute == null) return "";

                return attribute.Description;
            }
            catch (Exception ex)
            {
                return "";
            }
        }

        public static object GetEnumByDescription(Type type, string description)
        {
            object result = null;

            try
            {
                FieldInfo[] fieldInfos = type.GetFields();

                foreach (FieldInfo fieldInfo in fieldInfos)
                {
                    DescriptionAttribute attribute = Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute)) as DescriptionAttribute;
                    if (attribute?.Description == description)
                    {
                        result = Enum.Parse(type, fieldInfo.GetValue(null).ToString());
                        return result;
                    }
                }
            }
            catch (Exception ex)
            { }

            return result;
        }

        /// <summary>
        /// 获取枚举类型的成员数量
        /// </summary>
        public static int Length(this Enum enumValue)
        {
            return Enum.GetValues(enumValue.GetType()).Length;
        }

        /// <summary>
        /// 获取枚举类型的成员数量（泛型版本）
        /// </summary>
        public static int Count<T>(this T enumValue) where T : Enum
        {
            return Enum.GetValues(typeof(T)).Length;
        }

        /// <summary>
        /// 静态方法：直接通过类型获取长度
        /// </summary>
        public static int LengthOf<T>() where T : Enum
        {
            return Enum.GetValues(typeof(T)).Length;
        }
    }
}
